package com.alveole.events.browser;

import javax.ejb.EJB;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.alveole.dao.User;
import com.alveole.events.server.ErrorEvent;
import com.alveole.events.server.LoginEvent;
import com.alveole.objects.BrowserSession;

public class BrowserLoginEvent extends BrowserEvent {

	@PersistenceContext
	private EntityManager entityManager;

	@EJB
	private BrowserSession browserSession;
	
	String login;
	String password;
	
	
	
	public String getLogin() {
		return login;
	}



	public void setLogin(String login) {
		this.login = login;
	}



	public String getPassword() {
		return password;
	}



	public void setPassword(String password) {
		this.password = password;
	}



	@Override
	public void addServerEvents() {
		User u=null;
		
		Query q = entityManager.createQuery("select u from User u Where u.login=:login and u.password=:password");
		q.setParameter("login", login);
		q.setParameter("password", password);
		try{
			u = (User) q.getSingleResult();
		}
		catch (NoResultException e)
		{
			serverEvents.add(new ErrorEvent("User all login invalid"));
		}
		if (u!=null)
		{
			browserSession.setUser(u);
			serverEvents.add(new LoginEvent(browserSession.getUser().getLogin()));
		}
	}
}
